<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/9/3
 * Time: 16:11
 */

namespace ticket\modules\frontend\controllers;


use ticket\libs\Tools;
use ticket\modules\frontend\models\CategoryInfo;
use ticket\modules\frontend\models\TicketAdditional;
use ticket\modules\frontend\models\OrderDetails;
use ticket\modules\frontend\models\OrderInfo;
use ticket\modules\frontend\models\TicketCategorys;
use ticket\modules\frontend\models\TicketInfo;
use ticket\modules\frontend\models\TicketQuotaRule;
use Yii;
use yii\helpers\ArrayHelper;
use yii\base\Exception;
use yii\web\Controller;

class TicketCategoryController extends Controller
{
	
	public function actionIsTimce(){
		$res = 0;
		$post = Yii::$app->request->post();
		$count=0;
		if($post['phone']){
			$model = OrderDetails::find()->select(['oid'])->where(['phone'=>$post['phone'],'isvip'=>1])->indexBy('oid')->asArray()->all();
			$is_ok = OrderInfo::find()->where(['oid'=>array_keys($model),'order_status'=>[1,3]])->indexBy('oid')->asArray()->all();
			$count = OrderDetails::find()->where(['oid'=>array_keys($is_ok)])->sum('ticket_num');
			$count = $count==null?0:$count;
			if($count>=5)
				$res=1;
		}
		return Tools::showRes(0,'成功',['count'=>$count,'is_enough'=>$res,'all'=>5]);
	}

    
    /*** 获取分类列表
     * @return false|string
     */
    public function actionCategoryList()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $app_id = isset($post['appId'])?$post['appId']:'';
            $level = isset($post['level'])?$post['level']:0;  // 分类层级, 0->全部,1->1级
            $name = isset($post['name'])?$post['name']:'';  // 分类层级, 0->全部,1->1级
            if (empty($app_id)){
                return Tools::showRes(10404,'参数有误');
            }
            if (!empty($name)){
                $where = ['like','tk_ticket_categorys.cat_name',$name];
            }else{
                $where = [];
            }
            $categoryModel = TicketCategorys::find()->where('app_id = :aid and show_in_nav = :show',[':aid' => $app_id,':show' => 1])->andWhere($where)->joinWith(['category']);

            $categoryData = $categoryModel->select(['tk_ticket_categorys.cat_id','tk_ticket_categorys.cat_name','image_url','parent_id','cat_desc','link','sort', 'other_field'])->asArray()->all();
            $categoryList= $this->setTreeList($categoryData,0,$level);

            ArrayHelper::multisort($categoryList, ['sort'], [SORT_DESC]);

            return Tools::showRes(0,'success',[
                'categoryList' => $categoryList,
            ]);

        }
    }


    /*** 通过分类id获取门票
     * @return false|string
     */
    public function actionTicketByCategory()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $cid = isset($post['categoryId'])?$post['categoryId']:'';
            $app_id = isset($post['appId'])?$post['appId']:'';
            $childState = isset($post['child'])?$post['child']:false;
            if (empty($cid) or empty($app_id)){
                return Tools::showRes(10404,'参数有误');
            }

            if ($childState){
                $categoryId = TicketCategorys::find()->where('app_id = :aid and cat_id = :cid',[':aid' => $app_id,':cid' => $cid])->select(['cat_id','all_child_id'])->asArray()->one();
                if (!is_null($categoryId) and  $categoryId['all_child_id'] != 0){
                    $allChildId = explode(',',$categoryId['all_child_id']);
                    $allChildId[] = $categoryId['cat_id'];
                    $where = ['in','category',$allChildId];
                }else{
                    $where = ['category' => $cid];
                }
            }else{
                $where = ['category' => $cid];
            }

            $ticketList = TicketInfo::find()->where('app_id = :aid and state = :ste',[':aid' => $app_id,':ste' => 1])->andFilterWhere($where)->joinWith(['additional'])->with(['ticketDate'])->asArray()->all();
            $ticketData = [];
            foreach ($ticketList as $key => $val){
                if (!empty($val['additional']) and !empty($val['additional']['image_url'])){
                    $val['image_url'] = json_decode($val['additional']['image_url'],true)[0]['url'];
                }else{
                    $val['image_url'] = '';
                }
                if (!empty($val['ticketDate'])){
                    unset($val['additional'],$val['ticketDate']);
                    $ticketData[] = $val;
                }
            }
            $categoryInfo = $this->getCategoryInfo($cid);
            return Tools::showRes(0,'success',[
                'ticketList' => $ticketData,
                'categoryInfo' => $categoryInfo,
            ]);
        }
    }

    /**** 获取所有分类下的门票
     * @return false|string
     */
    public function actionCategoryTicket()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $app_id = isset($post['appId'])?$post['appId']:'';
            $cat_id = isset($post['catId'])?$post['catId']:'';
            if (empty($app_id)){
                return Tools::showRes(10404,'参数有误');
            }
            if (empty($cat_id)){
                $categoryModel = TicketCategorys::find()->where('tk_ticket_categorys.app_id = :aid',[':aid' => $app_id]);
            }else{
//                $categoryModel = TicketCategorys::find()->where('tk_ticket_categorys.app_id = :aid and show_in_nav = :show',[':aid' => $app_id,':show' => 1])->andWhere(['or',"cat_id=$cat_id",['like','all_parent_id',$cat_id]]);
                $categoryModel = TicketCategorys::find()->where('tk_ticket_categorys.app_id = :aid',[':aid' => $app_id])->andWhere(['or',"tk_ticket_categorys.cat_id=$cat_id",['parent_id' => $cat_id]]);
            }
            $nowTime = date("Y-m-d H:i:s");
            $ticketList = $categoryModel->select(['tk_ticket_categorys.cat_id','tk_ticket_categorys.cat_name','image_url','link','cat_desc','tk_ticket_categorys.sort'])->joinWith(['category'])->joinWith(['ticket'])->orderBy(['tk_ticket_categorys.sort' => SORT_DESC])->asArray()->all();
            $ticketData = [];
            if (!empty($ticketList)) {
                foreach ($ticketList as $key => $val) {
                    $ticketInfo[$key] = [
                        'cat_id' => $val['cat_id'],
                        'cat_name' => $val['cat_name'],
                        'image_url' => $val['image_url'],
                        'link' => $val['link'],
                        'cat_desc' => $val['cat_desc'],
                        'sort' => $val['sort'],
                        'category'=>$val['category'],
                        'ticket' => []
                    ];
                    if (!empty($val['ticket'])){
                        foreach ($val['ticket'] as $k => $v){
                            if (!empty($v['ticketDate']) and  !empty($v['rule'])){
                                unset($v['ticketDate']);
                                if ($v['rule']['online_time'] < $nowTime and $v['rule']['offline_time'] > $nowTime){
                                    unset($v['rule']);
                                    $v['buy_notice'] = $v['additional']['buy_notice'];
                                    $ticketInfo[$key]['ticket'][] = $v;
                                }
                            }
                        }

                    }
                    if (!empty($ticketInfo[$key]['ticket'])){
                        $ticketData[] = $ticketInfo[$key];
                    }
                }
                $categoryInfo = $this->getCategoryInfo($cat_id);
            }else{
                $categoryInfo = [];
            }
            return Tools::showRes(0,'success',[
                'ticketList' => $ticketData,
                'categoryInfo' => $categoryInfo,
            ]);

        }
    }



    /**** 获取所有分类下的门票
     * @return false|string
     */
    public function actionCategoryByTicket()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $app_id = isset($post['appId'])?$post['appId']:'';
            $cat_id = isset($post['catId'])?$post['catId']:'';
            if (empty($app_id) || empty($cat_id)){
                return Tools::showRes(10404,'参数有误');
            }
            $categoryModel = TicketCategorys::find()->where('tk_ticket_categorys.app_id = :aid',[':aid' => $app_id])->andWhere(['or',"cat_id=$cat_id",['like','all_parent_id',$cat_id]]);
            $ticketList = $categoryModel->select(['cat_id','cat_name','image_url','link','cat_desc','tk_ticket_categorys.sort'])->joinWith(['ticket'])->orderBy(['tk_ticket_categorys.sort' => SORT_DESC])->asArray()->all();
            $ticketData = [];
            if (!empty($ticketList)) {
                foreach ($ticketList as $key => $val) {
                    $ticketInfo[$key] = [
                        'cat_id' => $val['cat_id'],
                        'cat_name' => $val['cat_name'],
                        'image_url' => $val['image_url'],
                        'link' => $val['link'],
                        'cat_desc' => $val['cat_desc'],
                        'sort' => $val['sort'],
                        'ticket' => []
                    ];
                    if (!empty($val['ticket'])){
                        foreach ($val['ticket'] as $k => $v){
                            if (!empty($v['ticketDate'])){
                                unset($v['ticketDate']);
                                $v['buy_notice'] = $v['additional']['buy_notice'];
                                $ticketInfo[$key]['ticket'][] = $v;
                            }

                        }

                    }
                    if (!empty($ticketInfo[$key]['ticket'])){
                        $ticketData[] = $ticketInfo[$key];
                    }
                }
                $categoryInfo = $this->getCategoryInfo($cat_id);
            }else{
                $categoryInfo = [];
            }
            return Tools::showRes(0,'success',[
                'ticketList' => $ticketData,
                'categoryInfo' => $categoryInfo,
            ]);

        }
    }



    /** 恐龙园新加特殊门票信易游活动
     *
     *
     * @return false|string
     */
    public function actionTicketXinSwim()
    {
        if (Yii::$app->request->isPost){
            $tid = "108";
            $cat_id = '22';
            try{
                $ticketInfoModel = new TicketInfo();
                $info = $ticketInfoModel->getInfo($tid);
                $categoryInfo = $this->getCategoryInfo($cat_id);
                return Tools::showRes(0,'success',[
                    'ticketList' => $info,
                    'categoryInfo' => $categoryInfo,
                ]);

            }catch (Exception $e){
                return Tools::showRes(400,$e->getMessage());
            }
        }
    }

    /*** 获取门票分类详情
     * @param $cat_id
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getCategoryInfo($cat_id)
    {
        $categoryModel = new CategoryInfo();
        $info = $categoryModel->getInfo($cat_id);
        return $info;
    }


    /*
    递归函数
    返回一个 商品分类 树列表
    $arr        需要处理的数组
    $parent_id  从哪个分类
    */
    private  function setTreeList($arr, $parent_id, $levelStatus = '')
    {
        static $level = 0;//层级
        static $paramsData = [];
        $level++;
        $total = self::getNumById($arr, $parent_id);//此ID下有多少条数据
        $tmp = 0;//一共匹配到几个
        for($i=0; $i<count($arr); $i++){


            $arr[$i]["level"] = $level;
            $arr[$i]['image_url'] = json_decode($arr[$i]['image_url'],true)[0]['url'];

            if (!is_array($arr[$i]['other_field']) and !empty($arr[$i]['other_field'])){
                $arr[$i]['other_field'] = json_decode($arr[$i]['other_field'],true);
            }else{
                $arr[$i]['other_field'] = [];
            }
            if($arr[$i]["parent_id"] == $parent_id){
                $tmp++;//匹配到之后加1
                if($tmp == $total){
                    $end = 0;
                }else{
                    $end = 1;
                }
                if (!empty($levelStatus) and $arr[$i]['level'] == $levelStatus){
                    array_push($paramsData, $arr[$i]);
                }elseif(empty($levelStatus)) {
                    array_push($paramsData, $arr[$i]);
                }
                self::setTreeList($arr, $arr[$i]["cat_id"],$levelStatus);
            }
        }
        $level--;

        return $paramsData;
    }


    private function ticketQuota($tid)
    {
        $ticketQuotaInfo = TicketQuotaRule::find()->select(['qid','tid','online_time','offline_time'])->where('tid = :tid',[':tid' => $tid])->asArray()->one();
        if (!empty($ticketQuotaInfo)){
            $nowDate = date("Y-m-d H:i:s");
            if ($ticketQuotaInfo['offline_time'] > $nowDate and $ticketQuotaInfo['online_time'] < $nowDate){
                return true;
            }
        }
        return false;

    }







    /*
  为递归函数服务 能够确定前面的符号
  查看父id为 $parent_id 的 结果有多少个
  $arr        匹配的数组
  $parent_id  匹配的父ID
  */
    public static function getNumById($arr, $parent_id)
    {
        $num = 0;
        foreach($arr as $k => $v){
            if($v["parent_id"] == $parent_id){
                $num++;
            }
        }
        return $num;
    }




    /**** 获取所有分类下的门票
     * @return false|string
     */
    public function testCategoryTicket()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $app_id = isset($post['appId'])?$post['appId']:'';
            if (empty($app_id)){
                return Tools::showRes(10404,'参数有误');
            }

            $categoryModel = TicketCategorys::find()->where('tk_ticket_categorys.app_id = :aid and show_in_nav = :show',[':aid' => $app_id,':show' => 1]);
            $ticketList = $categoryModel->select(['cat_id','cat_name','image_url','link','cat_desc','tk_ticket_categorys.sort'])->joinWith(['ticket'])->orderBy(['tk_ticket_categorys.sort' => SORT_DESC])->asArray()->all();
            $ticketData = [];
            if (!empty($ticketList)) {
                foreach ($ticketList as $key => $val) {
                    $ticketInfo[$key] = [
                        'cat_id' => $val['cat_id'],
                        'cat_name' => $val['cat_name'],
                        'image_url' => $val['image_url'],
                        'link' => $val['link'],
                        'cat_desc' => $val['cat_desc'],
                        'sort' => $val['sort'],
                        'ticket' => []
                    ];
                    if (!empty($val['ticket'])){
                        foreach ($val['ticket'] as $k => $v){
                            if (!empty($v['ticketDate']) and !empty($v['rule'])){
                                $nowDate = date("Y-m-d H:i:s");
                                if ($v['rule']['offline_time'] > $nowDate and $v['rule']['online_time'] < $nowDate){
                                    unset($v['rule'],$v['ticketDate']);
                                    if ($v['category'] == $ticketInfo[$key]['cat_id']){
                                        $ticketInfo[$key]['ticket'][] = $v;
                                    }
                                }
                            }
                        }

                    }
                    if (!empty($ticketInfo[$key]['ticket'])){
                        $ticketData[] = $ticketInfo[$key];
                    }


                }
            }
            return Tools::showRes(0,'success',[
                'ticketList' => $ticketData,
            ]);

        }
    }

}